package com.project.nimsen.web.pub.tag;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.project.nimsen.util.NimsenUtil;

import freemarker.core.Environment;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public abstract class BaseTag implements TemplateDirectiveModel {
	HttpServletRequest request;
	Map params;
	Environment env;
	HttpSession session;
	boolean isrender = false;
	/**
	 * 得到session里的信息
	 * */
	public String getSessionAttr(String name){
		Object result = session.getAttribute(name);
		return NimsenUtil.obj2String(result);
	}
	/**
	 * 得到rquest里的属性值
	 * */
	public String getAttr(String name){
		Object result = request.getAttribute(name);
		return NimsenUtil.obj2String(result);
	}
	/**
	 * 得到rquest里的属性值
	 * */
	public Integer getIntegerAttr(String name){
		String result = getAttr(name);
		if(result==null)
			return null;
		return Integer.parseInt(result);
	}
	/**
	 * 从params参数中得到数据
	 * */
	public String getParam(String name){
		Object result = params.get(name);
		return NimsenUtil.obj2String(result);
	}
	/**
	 * 从params参数中得到数据
	 * */
	public Integer getIntegerParam(String name){
		String result = getParam(name);
		if(result==null)
			return null;
		return Integer.parseInt(result);
	}
	/**
	 * 接口的方法
	 * */
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		this.request = ((HttpRequestHashModel) env.getDataModel().get("Request")).getRequest();
		this.params = params;
		this.env = env;
		this.session = request.getSession();
		this.isrender = false;
		exec(env, params, loopVars, body);
		if(this.isrender)
		body.render(env.getOut());
	}
	/**
	 * 向页面输出对象
	 * @param outName  输出的对象名称
	 * @param outObj  输出的对象信息
	 * */
	protected void outVariable(String outName, Object outObj) throws TemplateModelException{
		env.setVariable(outName, ObjectWrapper.DEFAULT_WRAPPER.wrap(outObj));
		this.isrender = true;
	}
	/**
	 * 向页面写信息
	 * @param info 要写的信息内容
	 * @throws IOException 
	 * */
	protected void outWrite(String info) throws IOException{
		env.getOut().write(info);
	}
	
	protected abstract void exec(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException;
}
